package com.hmdp.utils;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

/**
 * 全局唯一ID生成策略
 */
@Component
public class RedisIdWorker {
    /**
     * 开始时间戳
     * ZoneOffset.UTC代表时区
     */
    private static final long BEGIN_TIMESTAMP = 1678147200;
    /**
     * 序列号位数
     */
    private static final int COUNT_BITS = 32;

    private StringRedisTemplate stringRedisTemplate;

    public RedisIdWorker(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public long nextId(String keyPrefix) {
        // 1.生成时间戳
        LocalDateTime now = LocalDateTime.now();
        long nowSecond = now.toEpochSecond(ZoneOffset.UTC);
        long timestamp = nowSecond - BEGIN_TIMESTAMP;

        // 2.生成序列号
        // 2.1.获取当前日期，精确到天
        String data = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        // 2.2.自增长拼接当天日期 increment -> icr redis自增id
        Long count = stringRedisTemplate.opsForValue().increment("icr:" + keyPrefix + ":" + data);

        // 3.拼接并返回（时间戳向左移动32位，然后用或运算实现拼接）
        return timestamp << COUNT_BITS | count;
    }

    /*  public static void main(String[] args) {
        // 指定本地日期时间
        LocalDateTime time = LocalDateTime.of(2023, 3, 7, 0, 0, 0);
        // 从1970-01-01T00:00:00Z开始到指定本地日期时间的秒数, 即时间戳
        Long second = time.toEpochSecond(ZoneOffset.UTC);
        System.out.println("seconds = " + second);
    }*/
}
